<template>
  <!-- <div class="mask" v-if="showMask"></div> -->
  <div class="box">
    <div class="box-content top_class">
      <el-table :data="getDataList1" :header-cell-style="tableColor" ref="upTableRef" style="width: 100%;"
        :height="tableH1">
        <el-table-column type="index" width="80" label="序号" align="center" show-overflow-tooltip>
          <template #default="scope">
            {{ (scope.$index + 1) + (currentPage - 1) * pageSize }}
          </template>
        </el-table-column>
        <!-- <el-table-column prop="thing" label="定值修改事件" align="center" show-overflow-tooltip />
        <el-table-column prop="start" label="开始时间" align="center" show-overflow-tooltip />
        <el-table-column prop="end" label="结束时间" align="center" show-overflow-tooltip />
        <el-table-column prop="count" label="信号总数" align="center" show-overflow-tooltip />
        <el-table-column label="信号详情" width="100" align="center" show-overflow-tooltip>
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="handleClick(row)">查看</el-button>
          </template>
        </el-table-column> -->
        <!-- <el-table-column prop="belonging_station" label="厂站名称" align="center" show-overflow-tooltip />
        <el-table-column prop="device" label="装置名称" align="center" show-overflow-tooltip /> -->
        <el-table-column prop="set_value_modification" label="事件名称" align="center" show-overflow-tooltip />
        <el-table-column prop="begin_time" label="开始时间" align="center" show-overflow-tooltip>
          <!-- <template #default="scope">
            {{ new Date(parseInt(scope.row.begin_time)).getFullYear() + '/' + (new
              Date(parseInt(scope.row.begin_time)).getMonth() + 1) + '/' +
              new Date(parseInt(scope.row.begin_time)).getDate() + ' ' + new Date(parseInt(scope.row.begin_time)).getHours()
              +
              ':' + new
                Date(parseInt(scope.row.begin_time)).getMinutes() + ':' + new
                  Date(parseInt(scope.row.begin_time)).getSeconds() }}
          </template> -->
        </el-table-column>
        <el-table-column prop="end_time" label="结束时间" align="center" show-overflow-tooltip>
          <!-- <template #default="scope">
            {{ new Date(parseInt(scope.row.end_time)).getFullYear() + '/' + (new
              Date(parseInt(scope.row.end_time)).getMonth() + 1) + '/' +
              new Date(parseInt(scope.row.end_time)).getDate() + ' ' + new Date(parseInt(scope.row.end_time)).getHours() +
              ':' + new
                Date(parseInt(scope.row.end_time)).getMinutes() + ':' + new Date(parseInt(scope.row.end_time)).getSeconds() }}
          </template> -->
        </el-table-column>
        <el-table-column prop="number" label="告警总数" align="center" show-overflow-tooltip />
        <el-table-column label="结果详情" width="100" align="center">
          <template #default="scope">
            <!-- <el-button link type="primary" size="small" @click="handleClick(scope.row)">查看</el-button> -->
            <el-tag @click="handleClick(scope.row)">查看</el-tag>
          </template>
        </el-table-column>
      </el-table>
      <div class="page-box">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </div>
    <!-- <div class="line-box"></div> -->
    <div class="box-content bottom_class">
      <div class='scroll-content'>
        <div class="modal-content"></div>
        <el-table :data="historyDataList1" :header-cell-style="tableColor" ref="tableRef" style="width: 100%"
          :height="tableH">
          <el-table-column type="index" width="60" label="序号" align="center" show-overflow-tooltip />
          <el-table-column prop="主站接收时间" label="主站接收时间" align="center" show-overflow-tooltip>
            {{ new Date().getFullYear() + '/' + (new Date().getMonth() + 1) + '/' + new Date().getDate() + ' ' + (new
              Date().getHours() >= 10 ? new Date().getHours() : '0' + new Date().getHours()) + ':' + (new
                Date().getMinutes() >= 10 ? new Date().getMinutes() : '0' + new Date().getMinutes()) + ':' + (new
                  Date().getSeconds() >= 10 ? new Date().getSeconds() : '0' + new Date().getSeconds()) }}
          </el-table-column>
          <el-table-column prop="所属厂站" label="所属厂站" align="center" show-overflow-tooltip />
          <el-table-column prop="装置" label="装置" align="center" width="350" show-overflow-tooltip />
          <el-table-column prop="遥信点" label="遥信点" align="center" width="350" show-overflow-tooltip />
          <el-table-column prop="值" label="值" align="center" show-overflow-tooltip />
          <el-table-column prop="prediction" label="标签" align="center" show-overflow-tooltip>
            <template #default="scope">
              <span v-show="scope.row.prediction === 1" class="isYes">是</span>
              <span v-show="scope.row.prediction === 0" class="isNo">否</span>
            </template>
          </el-table-column>
        </el-table>
      </div>

    </div>
  </div>
</template>
<script setup>
import { ref, onMounted, nextTick, onUnmounted, watch } from "vue";
import hisRecord from "@/api/hisRecord";

const baseTime = new Date().getTime()

const historyDataList1 = ref([])
const historyDataList = ref([])
const tableData = ref([])
const getDataList = ref([])
const getDataList1 = ref([])
let tableH = ref(0);
let tableH1 = ref(0);
let tableRef = ref()
let upTableRef = ref()
const currentPage = ref(1);
const pageSize = ref(20);
let total = ref(1);

let timer = null;
let upTimer = null;
let nums = 0

const props = defineProps({
  setStep: {
    type: Boolean,
    default: false
  }
});

watch(
  [() => props.setStep],
  () => {
    console.log('lengthsss props.setStep', props.setStep)
    if (!props.setStep) return
    const lengths = historyDataList1.value.length
    // console.log('lengthsss', lengths)
    nextTick(() => {
      const scrollDom = tableRef.value.$refs.bodyWrapper.getElementsByClassName("el-scrollbar__wrap")[0];
      // console.log('lengthsss scrollDom', scrollDom.scrollTop)
      scrollDom.scrollTop = lengths * 40
      // console.log('lengthsss scrollDom.scrollTop', scrollDom.scrollTop)
      emit("changeStep", false);
    })
    setTimeout(() => {
      const lengths = historyDataList1.value.length
      const scrollDom = tableRef.value.$refs.bodyWrapper.getElementsByClassName("el-scrollbar__wrap")[0];
      // console.log('lengthsss scrollDom down', scrollDom.scrollTop)
      scrollDom.scrollTop = lengths * 40
      // console.log('lengthsss scrollDom.scrollTop', scrollDom.scrollTop)
    }, 200)
  }
);

const easeStep = [5, 5, 5, 5, 5, 5, 5, 5, 0, 0, 0, 0]
const tableColor = {
  backgroundColor: '#F2F3F5',
  borderColor: '#F2F3F5',
}
const scroll = (timesss, nameRef, step) => {
  // 在执行新的计时器前将之前的计时器清除
  if (timesss) clearInterval(timesss);
  let status = true;
  // 获取表格滚动区域的dom
  const scrollDom = nameRef.$refs.bodyWrapper.getElementsByClassName("el-scrollbar__wrap")[0];
  // console.log('nameRef', nameRef)
  // console.log('scrollDom', scrollDom.getElementsByClassName('el-table__row')[0].offsetHeight)
  // scrollDom.style.transition = 'all 1s ease'
  // 增加监听事件鼠标移入停止滚动
  scrollDom.addEventListener('mouseover', () => {
    status = false;
  });
  // 鼠标移出恢复滚动
  scrollDom.addEventListener('mouseout', () => {
    status = true;
  });
  // 设置每秒滚动一行
  timesss = setInterval(() => {
    // console.log('status', status)
    if (status) {
      // nums++
      // if (nums % 20 === 0) {
      //   setDataList(getDataList.value, (nums / 20) + '')
      // }
      // console.log(easeStep[(nums % 5 === 0 ? 4 : (nums % 5 - 1))])
      // 设置每次滚动的像素
      // scrollDom.scrollTop += easeStep[(nums % 12 === 0 ? 11 : (nums % 12 - 1))];
      scrollDom.scrollTop += step
      // console.log('scrollDom.scrollTop', scrollDom.scrollTop)
      // 当滚动到底部时修改scrollTop回到顶部
      if ((scrollDom.scrollHeight - (scrollDom.clientHeight + scrollDom.scrollTop)) < 1) {
        // scrollDom.scrollTop = 0;
      }
    }
    //控制速度
  }, 200);
}
const handleSizeChange = (val) => {
  console.log(`${val} items per page`);
  currentPage.value = 1;
  pageSize.value = val;
  pageData.value = getPagedData();
};

const handleCurrentChange = (val) => {
  console.log(`current page: ${val}`);
  currentPage.value = val;
  // pageData.value = getPagedData();
};
// const setDataList = (data, num) => {
//   // console.log('num', num)
//   // console.log('data', data)
//   if (data) {
//     // getDataList.value.push(data[num])
//     let arr = data.filter(item => {
//       // console.log('item', Number(item.set_value_modification), num)
//       return item.set_value_modification == num
//     })
//     // console.log('arr', arr)
//     if (arr && arr.length > 0)
//       getDataList1.value = getDataList1.value.concat(arr)
//   }
// }
//设置定时器进行自滚动
const getData = () => {
  setTimeout(() => { scroll(timer, tableRef.value, 40) }, 5)
}
const upGetData = () => {
  setTimeout(() => { scroll(upTimer, upTableRef.value, 40) }, 5)
}
onUnmounted(() => {
  // 组件卸载记得清除计时器
  if (timer) clearInterval(timer);
  timer = null;

  if (upTimer) clearInterval(upTimer);
  upTimer = null;
})

onMounted(async () => {
  nextTick(() => {
    tableH1.value = (window.innerHeight - 100) / 2;
    tableH.value = (window.innerHeight - 100) / 2 - 140;
  });
  await setClean()
  await onLoad();
});
const setClean = () => {
  return hisRecord
    .setClean({ baseTime: baseTime, data_info: [] })
    .then((res) => {
      console.log(res.data);
    })
    .catch((err) => {
      console.log(err);
    });
}
const getDataGrp = () => {
  hisRecord
    .getHisRecordList1({
      out_file: "out_20240704063943_test_data.xlsx"
    })
    .then((res) => {
      console.log(res.data);
      // 1:正常；0:异常；
      if (res && res.data.code === 1) {
        getDataList.value = [];
        if (res.data.data_grp) {
          getDataList.value = res.data.data_grp
          // for (const key in res.data.data.data_info) {
          //   const obj = res.data.data.data[key];
          //   historyDataList.value.push(obj);
          // }
        } else {
          getDataList.value = [];
        }
      }
    })
    .catch((err) => {
      console.log(err);
    });
}
const setYesList = (list) => {
  let data = { baseTime: baseTime, data_info: list }
  hisRecord
    .setYesList(data)
    .then((res) => {
      // console.log(res.data);
      // 1:正常；0:异常；
      if (res && res.data.code === 1) {
        getDataList1.value = res.data.data_grp
      }
    })
    .catch((err) => {
      console.log(err);
    });
}
const addUpData = (data, num, type) => {
  const randomNum = num
  const length = historyDataList1.value.length
  // console.log('length', length)
  let arrs = []
  for (let i = 0; i < randomNum; i++) {
    if (length === 0) {
      arrs.push(data[i])
    } else {
      if (length + i <= data.length - 1) {
        arrs.push(data[length + i])
      }
    }
  }
  // console.log('arrs', arrs)
  // arrs.forEach(item => {
  //   item.主站接收时间 = new Date().getFullYear() + '/' + (new Date().getMonth() + 1) + '/' + new Date().getDate() + ' ' + (new Date().getHours() >= 10 ? new Date().getHours() : '0' + new Date().getHours()) + ':' + (new Date().getMinutes() >= 10 ? new Date().getMinutes() : '0' + new Date().getMinutes()) + ':' + (new Date().getSeconds() >= 10 ? new Date().getSeconds() : '0' + new Date().getSeconds())
  // })
  const hasBiaoqian = arrs.filter(item => {
    return item.prediction === 1
  })
  // console.log('type', type)
  // console.log('hasBiaoqian', hasBiaoqian)
  if (hasBiaoqian && hasBiaoqian.length > 0) {
    if (type === 'second') {
      hasBiaoqian.forEach(item => {
        // item.主站接收时间 = new Date(item.主站接收时间).getTime()
        item.主站接收时间 = new Date().getTime()
      })
    } else {
      hasBiaoqian.forEach(item => {
        let dates = new Date()
        dates.setDate(new Date().getDate() - 1)
        dates.setHours(new Date(item.主站接收时间).getHours())
        dates.setMinutes(new Date(item.主站接收时间).getMinutes())
        dates.setSeconds(new Date(item.主站接收时间).getSeconds())
        item.主站接收时间 = new Date(dates).getTime()
      })
    }
    // console.log('hasBiaoqian down', hasBiaoqian)
    setYesList(hasBiaoqian)
  }

  historyDataList1.value = historyDataList1.value.concat(arrs)
  // console.log('legnth down ', historyDataList1.value.length)
}
const randoms = (data) => {
  let nums = 530
  let timerRandom = null
  addUpData(data, nums, 'first')
  nextTick(() => {
    const scrollDom = tableRef.value.$refs.bodyWrapper.getElementsByClassName("el-scrollbar__wrap")[0];
    scrollDom.scrollTop = nums * 40

    timerRandom = setInterval(() => {
      addUpData(data, Math.random() * 4 + 3, 'second')
      // }, (Math.random() * 500) + 500)
    }, 2000)
  })
}
/** 加载数据 */
const onLoad = () => {
  hisRecord
    .getSlide()
    .then((res) => {
      console.log(res.data);
      // 1:正常；0:异常；
      if (res && res.data.code === 1) {
        historyDataList.value = [];
        if (res.data.data_info) {
          historyDataList.value = res.data.data_info
          randoms(historyDataList.value)
          // for (const key in res.data.data.data_info) {
          //   const obj = res.data.data.data[key];
          //   historyDataList.value.push(obj);
          // }

          getData()
          upGetData()
        } else {
          historyDataList.value = [];
        }
        getDataGrp()
      }
    })
    .catch((err) => {
      console.log(err);
    });
};
// row, column,
const formatterStatus = (cellVal) => {
  let text = "";
  switch (cellVal) {
    case 1:
      text = "推理中";
      break;
    case 0:
      text = "已完成";
      break;
    case -1:
      text = "推理失败";
      break;
  }
  return text;
};

// 下方表格逻辑
const handleClick = (row) => {
  // 筛选上面表格数据
  console.log("click", row);
  // const time = new Date().getTime();
  console.log('baseTime', baseTime)
  emit("changeStep", true);
  emit("tabVal", true, row.out_file, row.out_file, baseTime, row.set_value_modification, { begin: row.begin_time, end: row.end_time });
};

const emit = defineEmits(["tabVal", "changeStep"]);
</script>
<style scoped>
:deep(.el-scrollbar) {
  transition: all 1s ease
}

:deep(.el-scrollbar__view) {
  transition: all 1s ease
}

:deep(.el-table__body) {
  transition: all 1s ease
}

:deep(.el-table__body) {
  will-change: transform;
  transition: all 1s ease;
}

:deep(.el-table__body-wrapper) {
  transition: all 1s ease;
}

.box {
  width: 100%;
  height: 100%;
  position: relative;
  background-color: transparent;
}

.line-box {
  border: 1px solid #2590ff;
  margin-bottom: 5px;
}

.box-content {
  position: relative;
  overflow: auto;
  padding: 10px;
  border-radius: 10px;
  background-color: #fff;

  .scroll-content {
    /* border: 1px solid #2590ff; */
  }
}

.top_class {
  border-radius: 0 0 10px 10px;
  height: calc(60% - 5px);
  color: #1D2129;
}

.bottom_class {
  border-radius: 10px;
  margin-top: 10px;
  border: 5px solid rgb(227, 224, 224);
  height: calc(40% - 5px);
}

.modal-content {
  height: 100%;
  position: absolute;
  width: 100%;
  top: 0;
  left: 0;
  z-index: 10;
}

.page-box {
  margin-top: 10px;
  height: 30px;
  float: right;
}

.upload-box {
  text-align: center;
  padding-right: 30px;
  /* margin-top: 30px;
  padding-bottom: 30px; */
}

.mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 9999;
}

.button-div {
  display: flex;
  justify-content: center;
  margin: 30px auto;
}

.header_class {
  background-color: red;
}

.isYes {
  color: blue;
}

.isNo {
  color: red;
}

.el-tag {
  cursor: pointer;
}
</style>
